/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.solr.schema;

import java.io.InputStream;
import java.net.URL;

import com.pingan.haofang.searchcloud.api.schema.IndexSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pingan.haofang.searchcloud.solr.constants.SolrConstant;

/**
 * @author huhailiang937
 * @date 2017年5月3日下午8:54:20
 * @since 1.0.0
 */
public class SolrCloudXmlGenerater {

    protected static Logger LOG = LoggerFactory.getLogger(SolrCloudXmlGenerater.class);

    protected static final String FILE_SEPARATOR = System.getProperty("file.separator");

    public static final String SCHEMA_NAME = "managed-schema";

    public static final String SOLR_CONFIG_NAME = "solrconfig.xml";

    public void generatorIndexSchemaXml(IndexSchema schema) throws Exception {
        String templet = SolrConstant.SCHEMA_TEMPLET_ROOT + SCHEMA_NAME + ".vm";
        String indexSchemaXml = GeneraterEngine.generator(schema, templet);
        LOG.debug(String.format("indexSchemaXml:\n%s", indexSchemaXml));
        String indexXmlSavePath = getGeneratorDir(schema.getIndexName()) + SCHEMA_NAME;
        GeneraterFileWriteSupport.writeGeneratorCoder(indexSchemaXml, indexXmlSavePath);
    }

    public void generatorSolrconfigXml(IndexSchema schema) throws Exception {
        this.generatorXml(schema, SolrConstant.SOLR_CONFIG_XML);
    }

    public void generatorOthersXml(IndexSchema schema) throws Exception {
        for (String configName : SolrConstant.SOLR_OTHERS_CONFIGS) {
            generatorXml(schema, configName);
        }

        for (String configName : SolrConstant.SOLR_LANG_CONFIGS) {
            generatorXml(schema, "lang/"+configName);
        }
    }

    private void generatorXml(IndexSchema schema, String configName) throws Exception {
        InputStream in = SolrCloudXmlGenerater.class.getResourceAsStream( configName);
        int i = -1;
        byte[] b = new byte[1024];
        StringBuffer sb = new StringBuffer();
        try {
            while ((i = in.read(b)) != -1) {
                sb.append(new String(b, 0, i));
            }
        } catch (Exception e) {
            throw new RuntimeException("generatorXml has error:", e);
        }

        String xml = sb.toString();
        LOG.debug(String.format("xml:\n%s", xml));
        String indexXmlSavePath = getGeneratorDir(schema.getIndexName()) + configName;

        GeneraterFileWriteSupport.writeGeneratorCoder(xml, indexXmlSavePath);

        LOG.info("write : " + indexXmlSavePath);
    }

    public String getGeneratorDir(String indexName) {
        URL url = SolrCloudXmlGenerater.class.getClassLoader().getResource("");
        return url.getPath() + SolrConstant.SOLR_CONFIG_SAVE_PATH + FILE_SEPARATOR + indexName + FILE_SEPARATOR;
    }

}
